import {
  $wuxDialog
} from '../../../miniprogram_npm/wux-weapp/index'
import {
  getMineCertificateList
} from '../../../api/certificate';
import {
  removeBadge
} from '../../../api/other';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIOS: false,
    certificateBadge: [],
    certificateList: [],
    pageNo: 1,
    rowCount: 0,
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const {
      certificate
    } = getApp().globalData.unRead;
    this.setData({
      certificateBadge: certificate,
      isIOS: getApp().globalData.isIOS,
    })
    this.data.pageNo = 1;
    this.data.certificateList.length = 0;
    this.loadMineCertificateList();
  },

  /**
   * 加载我的证书列表
   */
  loadMineCertificateList() {
    getMineCertificateList(this.data.pageNo).then(res => {
      // 判断是否显示红点
      res.list = res.list.map(item => {
        if (this.data.certificateBadge.includes(item.id)) {
          item.badge = true;
        } else {
          item.badge = false;
        }
        return item;
      })
      this.setData({
        certificateList: this.data.certificateList.concat(res.list),
        rowCount: res.rowCount,
      })
    })
  },

  /**
   * 查看驳回原因
   * @param {object} e 
   */
  handleOpenReasonDialog(e) {
    const {
      id,
      applyId,
      reason
    } = e.target.dataset;
    this.clearBadge(applyId);
    $wuxDialog().confirm({
      title: '未通过原因',
      content: reason,
      buttons: [{
        text: '知道了',
      }, {
        text: '重新申请',
        type: 'primary',
        onTap(e) {
          wx.navigateTo({
            url: '/pages/credentials/enroll/enroll?id=' + id,
          })
        }
      }],
    })
  },

  /**
   * 进入证书详情
   * @param {object} e
   */
  navigatorCertificate(e) {
    const {
      applyId,
      certificateId
    } = e.currentTarget.dataset;
    this.clearBadge(applyId);
    wx.navigateTo({
      url: '/pages/credentials/detail/detail?isMine=1&id=' + certificateId,
    })
  },

  /**
   * 消除红点
   * @param {number} id 证书申请编号
   */
  clearBadge(id) {
    getApp().globalData.unRead.certificate = this.data.certificateBadge.filter(item => item !== id);
    let list = this.data.certificateList.map(item => {
      if (item.id === id) {
        item.badge = false;
      }
      return item;
    })

    removeBadge(1, id);
    this.setData({
      certificateList: list
    })
  },

  /**
   * 进入信息页面
   * @param {object} e
   *  - type: 0-信息展示 1-支付
   */
  navigatorInformation(e) {
    const {
      applyId,
      type
    } = e.currentTarget.dataset;
    this.clearBadge(applyId);
    wx.navigateTo({
      url: `/pages/credentials/info/info?id=${applyId}&type=${type}`,
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.rowCount > this.data.certificateList.length) {
      this.data.pageNo += 1;
      this.loadMineCertificateList();
    }
  },

})